//
//  CYMyHistoryViewController.m
//  cyydt
//
//  Created by chu on 2019/2/3.
//  Copyright © 2019 chu. All rights reserved.
//

#import "CYMyHistoryViewController.h"

#import "CYInformationNoImageTableViewCell.h"
#import "CYInfomationThreeImageTableViewCell.h"
#import "CYInformationOneImageTableViewCell.h"
#import "CYJingPinWenDaTableViewCell.h"

#import "CYArcitleDetailsViewController.h"
#import "CYHomeVideoDetailsViewController.h"
#import "CYProjectDetailViewController.h"
#import "CYWenDaDetailViewController.h"

@interface CYMyHistoryViewController ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
{
    NSString *_itemId;
    NSString *_userId;
}
@property (nonatomic, strong) NSMutableArray *lastDataArr;

@property (nonatomic, strong) NSMutableArray *dataSourceArr;

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation CYMyHistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [self.view addSubview:self.tableView];
    [self getData];
    self.title = @"浏览记录";
    self.tableView.estimatedRowHeight = 44;
    if (@available(iOS 11.0, *)) {
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self RightsetupNavgationItemWithpictureName:@"history_delete"];
}

- (void)RighttouchEvent{
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"history"];
    [[XBRequest sharedInstance] deleteDataWithUrl:url Parameter:nil ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"动态 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                [self getData];
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSourceArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *arr = self.dataSourceArr[section];
    return arr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *arr = self.dataSourceArr[indexPath.section];
    
    CYProjectModel *model = arr[indexPath.row];
    if ([model.type integerValue] == 7) {
        if ([NSString stringIsNull:model.images]) {
            CYInformationNoImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYInformationNoImageTableViewCell"];
            if (!cell) {
                cell = [[NSBundle mainBundle] loadNibNamed:@"CYInformationNoImageTableViewCell" owner:nil options:nil][0];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model = model;
            return cell;
        }else{
            NSArray *img = [model.images componentsSeparatedByString:@","];
            if (img.count >= 3) {
                CYInfomationThreeImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYInfomationThreeImageTableViewCell"];
                if (!cell) {
                    cell = [[NSBundle mainBundle] loadNibNamed:@"CYInfomationThreeImageTableViewCell" owner:nil options:nil][0];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.model = model;
                return cell;
            }else{
                CYInformationOneImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYInformationOneImageTableViewCell"];
                if (!cell) {
                    cell = [[NSBundle mainBundle] loadNibNamed:@"CYInformationOneImageTableViewCell" owner:nil options:nil][0];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.model = model;
                return cell;
            }
        }
        
    }else if ([model.type integerValue] == 3){
        CYInfomationThreeImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYInfomationThreeImageTableViewCell"];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"CYInfomationThreeImageTableViewCell" owner:nil options:nil][0];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.projectModel = model;
        cell.label2.text = @"";
        cell.label3.text = @"";
        return cell;
    }else if ([model.type integerValue] == 4){
        CYJingPinWenDaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYJingPinWenDaTableViewCell"];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"CYJingPinWenDaTableViewCell" owner:nil options:nil][0];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
    }else{
        CYInformationOneImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYInformationOneImageTableViewCell"];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"CYInformationOneImageTableViewCell" owner:nil options:nil][0];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.videoModel = model;
        return cell;
    }

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *arr = self.dataSourceArr[indexPath.section];
    CYProjectModel *model = arr[indexPath.row];
    if ([model.type integerValue] == 7) {
        if ([NSString stringIsNull:model.images]) {
            return UITableViewAutomaticDimension;
        }else{
            NSArray *img = [model.images componentsSeparatedByString:@","];
            if (img.count >= 3) {
                return UITableViewAutomaticDimension;
            }else{
                return 120;
            }
        }
    }else if ([model.type integerValue] == 3){
        return UITableViewAutomaticDimension;
    }else if ([model.type integerValue] == 4){
        return UITableViewAutomaticDimension;
    }else{
        return 120;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = RGBOF(0xF4F5FA);
    [view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSArray *arr = self.dataSourceArr[section];
    if (arr.count > 0) {
        CYProjectModel *model = [arr firstObject];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 12, kWindowW - 30, 20)];
        label.textColor = RGBOF(0x999999);
        label.font = [UIFont systemFontOfSize:14];
        label.text = model.msg;
        [view addSubview:label];
    }
    return view;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *arr = self.dataSourceArr[indexPath.section];
    CYProjectModel *model = arr[indexPath.row];
    if ([model.type integerValue] == 7) {
        CYArcitleDetailsViewController *detail = [[CYArcitleDetailsViewController alloc] init];
        detail.articleId = [model.ID stringValue];
        [[AppDelegate sharedAppDelegate] pushViewController:detail];
    }else if ([model.type integerValue] == 3){
        CYProjectDetailViewController *detail = [[CYProjectDetailViewController alloc] init];
        detail.model = model;
        [[AppDelegate sharedAppDelegate] pushViewController:detail];
    }else if ([model.type integerValue] == 4){
        CYWenDaDetailViewController *detail = [[CYWenDaDetailViewController alloc] init];
        detail.wedaId = [model.ID stringValue];
        [[AppDelegate sharedAppDelegate] pushViewController:detail];
    }else if ([model.type integerValue] == 28){
        CYHomeVideoDetailsViewController *detail = [[CYHomeVideoDetailsViewController alloc] init];
        detail.videoId = [model.ID stringValue];
        [[AppDelegate sharedAppDelegate] pushViewController:detail];
    }
}
#pragma mark - DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"wuneir"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"当前页面没有内容！";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:RGBOF(0x999999)
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    // 空白页面被点击时开启动画，reloadEmptyDataSet
    [self getData];
}


- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, kWindowH - Height_NavBar) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = BackGroundColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self getData];
        }];
        
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self getMoreData];
        }];
        
        [_tableView registerNib:[UINib nibWithNibName:@"CYInformationNoImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYInformationNoImageTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"CYInfomationThreeImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYInfomationThreeImageTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"CYInformationOneImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYInformationOneImageTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"CYInformationOneImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYInformationOneImageTableViewCell"];

    }
    return _tableView;
}

- (NSMutableArray *)dataSourceArr{
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}

- (void)getData{
    self.page = 1;
    [EasyShowLodingView showLoding];
    __weak typeof(self)weakself = self;
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"getBrowseRecord"];
    NSDictionary *param = @{@"pageNo":@1};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"历史 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([weakself.tableView.mj_header isRefreshing]) {
            [weakself.tableView.mj_header endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [weakself.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                [weakself.tableView removeFromSuperview];
                [weakself.view addSubview:weakself.tableView];
                NSDictionary *data = responseResult[@"data"];
                NSArray *list = data[@"list"];
                [weakself.dataSourceArr removeAllObjects];
                [weakself.lastDataArr removeAllObjects];
                NSMutableArray *muArr = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary *dic in list) {
                    CYProjectModel *model = [CYProjectModel mj_objectWithKeyValues:dic];
                    [muArr addObject:model];
                    [weakself.lastDataArr addObject:model];
                }
                if (muArr.count > 0) {
                    for (int i = 0; i < muArr.count; i ++) {
                        CYProjectModel *lab = muArr[i];
                        NSMutableArray *tempArray = [@[] mutableCopy];
                        [tempArray addObject:lab];
                        NSLog(@"====0000======");
                        for (int j = i+1; j < muArr.count; j ++) {
                            CYProjectModel *jlab = muArr[j];
                            if([lab.msg isEqualToString:jlab.msg]){
                                [tempArray addObject:jlab];
                                NSLog(@"====11====");
                                [muArr removeObjectAtIndex:j];
                                j -= 1;
                            }
                        }
                        [weakself.dataSourceArr addObject:tempArray];
                    }
                }
                
            }else{
                
            }
            [self.tableView reloadData];
            
        }
    }];
}

- (void)getMoreData{
    self.page ++;
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"getBrowseRecord"];
    NSDictionary *param = @{@"pageNo":[NSNumber numberWithInteger:self.page]};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"动态 ---- %@",responseResult);
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
            self.page--;
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSDictionary *data = responseResult[@"data"];
                NSArray *list = data[@"list"];
                NSMutableArray *muArr = [NSMutableArray arrayWithCapacity:0];
                [muArr addObjectsFromArray:self.lastDataArr];
                for (NSDictionary *dic in list) {
                    CYProjectModel *model = [CYProjectModel mj_objectWithKeyValues:dic];
                    [muArr addObject:model];
                }
                if (muArr.count > 0) {
                    [self.dataSourceArr removeAllObjects];
                    for (int i = 0; i < muArr.count; i ++) {
                        CYProjectModel *lab = muArr[i];
                        NSMutableArray *tempArray = [@[] mutableCopy];
                        [tempArray addObject:lab];
                        NSLog(@"====0000======");
                        for (int j = i+1; j < muArr.count; j ++) {
                            CYProjectModel *jlab = muArr[j];
                            if([lab.msg isEqualToString:jlab.msg]){
                                [tempArray addObject:jlab];
                                NSLog(@"====11====");
                                [muArr removeObjectAtIndex:j];
                                j -= 1;
                            }
                        }
                        [self.dataSourceArr addObject:tempArray];
                    }
                }
                
            }else{
                self.page --;
            }
            [self.tableView reloadData];
        }
    }];
}

- (NSMutableArray *)lastDataArr{
    if (!_lastDataArr) {
        _lastDataArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _lastDataArr;
}

@end
